//
//  WHYNetworkTools.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/23.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import Alamofire

//import AFNetworking

//enum WHYRequestMethod: String {
//    case GET = "GET"
//    case POST = "POST"
//}

class WHYNetWorkTools {
    

    // MARK: 应用程序信息
    private let appKey = "2796739057"
    private let appAecret = "5333e3005b2d982bfe0f3efc732cfe85"
    private let redirectUri = "http://www.baidu.com"
    
    /// 请求回调闭包的类型
    typealias WHYRequestCallBack = (result:AnyObject?, error: NSError?) -> ()
    
    static let sharedTools: WHYNetWorkTools = {
        let tool = WHYNetWorkTools()
        
//        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    
    
}

// MARK: - sendStatus
extension WHYNetWorkTools {
    
    func sendStatus(status: String, image: UIImage?, finished: WHYRequestCallBack) {
        
        var parameters = [String: AnyObject]()
        parameters["status"] = status
        
        if image == nil {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            tokenRequest(.POST, urlString: urlString, parameters: parameters, finished: finished)
        }else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let data = UIImagePNGRepresentation(image!)!
            
            upload(urlString, data: data, name: "pic", parameters: parameters, finished: finished)
        }
    }
    
}

// MARK: - 微博数据
extension WHYNetWorkTools {
    
    func loadStatus(since_id since_id: Int, max_id: Int, finished: WHYRequestCallBack) {
        
        var parameter = [String: AnyObject]()
        
        if since_id > 0 {
            parameter["since_id"] = since_id
        }else if max_id > 0 {
            parameter["max_id"] = max_id - 1//上拉加载数据时，加载倒数第二条数据后面的数据
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        tokenRequest(.GET, urlString: urlString, parameters: parameter, finished: finished)
        
    }
    
}

// MARK: - OAuth
extension WHYNetWorkTools {
    
    // MARK: OAuthURL
    /// - see [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        return NSURL(string: str)!
    }
    
// MARK: - 加载用户信息
    /// 加载用户信息
    ///
    /// - parameter uid:          uid
    /// - parameter access_token: access_token description
    /// - parameter finished:     finished description
    func loadUserInfo(uid: String, finished: WHYRequestCallBack) {
        var parameter = [String: AnyObject]()

        let urlString = "https://api.weibo.com/2/users/show.json"
        parameter["uid"] = uid

        tokenRequest(.GET, urlString: urlString, parameters: parameter, finished: finished)
    }
    
// MARK: - 加载访问令牌
    func loadAccessToken(code: String, finished: WHYRequestCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id": appKey,
                                          "client_secret": appAecret,
                                          "grant_type": "authorization_code",
                                          "code": code,
                                          "redirect_uri": redirectUri,]
        
        request(.POST, urlString: urlString, parameters: parameters, finished: finished)
    }
    
    
}

// MARK: - request
extension WHYNetWorkTools {
    /// token请求
    ///
    /// - parameter method:     请求方法
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数字典
    /// - parameter finished:   完成回调闭包
    private func tokenRequest (method: Alamofire.Method, urlString: String, var parameters: [String: AnyObject]?, finished: WHYRequestCallBack) {
        
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "weibo.error", code: -1001, userInfo: ["message" : "token为空"]))
            return
        }
        
        request(method, urlString: urlString, parameters: parameters, finished: finished)
        
    }
    
    /// 生成并监测 token 字典
    ///
    /// - parameter parameters: 参数字典
    ///
    /// - returns: 是否成功
    private func appendToken (inout parameters: [String: AnyObject]?) -> Bool {
        
        guard let token = WHYUserAccountViewModel.sharedUserAccount.userAccount?.access_token else {
            return false
        }
        
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token
        
        return true
    }
    
    /// 请求
    ///
    /// - parameter method:     请求方法
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数字典
    /// - parameter finished:   完成回调闭包
    private func request (method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]?, finished: WHYRequestCallBack) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        Alamofire.request(method, urlString, parameters: parameters).responseJSON { (response) -> Void in
            
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            
            if response.result.isFailure {
                QL4("网络请求错误  \(response.result.error)")
            }
            
            finished(result: response.result.value, error: response.result.error)
            
        }
        
        
//        --------------------------------------
//        AFN 网络请求
        
//        let sucess = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
//            
//            finished(result: result, error: nil)
//            
//        }
//        
//        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
//            
//            QL4(error)
//            finished(result: nil, error: error)
//            
//        }
//        
//        if method == WHYRequestMethod.GET {
//            GET(urlString, parameters: parameters, success: sucess, failure: failure)
//        }else if method == WHYRequestMethod.POST {
//            POST(urlString, parameters: parameters, success: sucess, failure: failure)
//        }
        
    }
    
    
    private func upload(urlString: String, data: NSData, name: String, var parameters: [String: AnyObject]?, finished: WHYRequestCallBack) {
        
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "weibo.error", code: -1001, userInfo: ["message" : "token为空"]))
            return
        }
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        Alamofire.upload(.POST, urlString, multipartFormData: { (formData) -> Void in
//              追加文件
                formData.appendBodyPart(data: data, name: name, fileName: "why", mimeType: "application/octet-stream")
//            追加字典
            if let para = parameters {
                
                for (key, value) in para {
                    
                    if let str = value as? String {
                        let strData = str.dataUsingEncoding(NSUTF8StringEncoding)!
                        
                        formData.appendBodyPart(data: strData, name: key)
                    }
                    
                }
                
            }
            
            
            }, encodingMemoryThreshold: 5 * 1024 * 1024) { (encodingResult) -> Void in
                
                switch encodingResult {
                case .Success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                    upload.responseJSON(completionHandler: { (response) -> Void in
                        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                        
                        if response.result.isFailure {
                            QL4("网络请求错误  \(response.result.error)")
                        }
                        
                        finished(result: response.result.value, error: response.result.error)
                        
                    })
                    break
                case .Failure(let encodingError):
                    QL4("上传文件编码错误  \(encodingError)")
                }
                
        }
        
        
//        ---------------------------------------
//        AFN  上传文件
        
//        let sucess = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
//            
//            finished(result: result, error: nil)
//            
//        }
        
//        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
//            
//            QL4(error)
//            finished(result: nil, error: error)
//            
//        }
        
//        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
//            formData.appendPartWithFileData(data, name: name, fileName: "OMG", mimeType: "application/octet-stream")
//            }, success: sucess, failure: failure)
        
    }
    
}





